# backend/routers/borrow_router.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from backend.database import get_db
from backend.dependencies import get_current_active_user, get_library_admin
from backend.models import User, LibraryMember
from backend.schemas import BorrowRecord
from backend.services import borrow_service
from backend.crud import borrow_crud

router = APIRouter()


@router.post("/borrow", response_model=BorrowRecord)
def borrow_book(
        book_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    return borrow_service.borrow_book(db, book_id, current_user.id)


@router.post("/borrow/approve/{record_id}", response_model=BorrowRecord)
def approve_borrow(
        record_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    # 需要验证当前用户是否有审批权限
    record = borrow_crud.get_borrow_record(db, record_id)
    if not record:
        raise HTTPException(status_code=404, detail="记录不存在")

    # 检查用户是否属于同一书阁
    if not db.query(LibraryMember).filter(
            LibraryMember.library_id == record.book.library_id,
            LibraryMember.user_id == current_user.id
    ).first():
        raise HTTPException(status_code=403, detail="无权审批")

    return borrow_service.approve_borrow(db, record_id, current_user.id)


@router.post("/return/{record_id}", response_model=BorrowRecord)
def return_book(
        record_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    return borrow_service.return_book(db, record_id)
